package com.yunche.yunchebusiness.ui.activity.main

import com.yunche.yunchebusiness.R
import com.yunche.yunchebusiness.api.Api
import com.yunche.yunchebusiness.base.BaseActivity
import com.yunche.yunchebusiness.common.CommonDialog
import com.yunche.yunchebusiness.common.Constant
import com.yunche.yunchebusiness.entity.LoginEntity
import com.yunche.yunchebusiness.isPhone
import com.yunche.yunchebusiness.mvp.contract.LoginContract
import com.yunche.yunchebusiness.mvp.presenter.LoginPresenter
import com.yunche.yunchebusiness.ui.activity.MainActivity
import com.yunche.yunchebusiness.utils.SpHelper
import com.yunche.yunchebusiness.utils.ToastyUtils
import kotlinx.android.synthetic.main.activity_login.*

class LoginActivity : BaseActivity(), LoginContract.View {

    private val mPresenter by lazy {
        LoginPresenter()
    }

    override fun loginSuccess(loginEntity: LoginEntity) {
        SpHelper.putValue(Constant.SP_KEY.TOKEN, loginEntity.token)
        SpHelper.putValue(Constant.SP_KEY.USER_NAME, et_login_phone.text.toString())
        SpHelper.putValue(Constant.SP_KEY.PASSWORD, et_login_password.text.toString())
        SpHelper.putValue(Constant.SP_KEY.TENANT_ID, loginEntity.id)
        ToastyUtils.showSuccess("登录成功")
        if (loginEntity.checkTenant) {
            openActivity(MainActivity::class.java)
            finish()
        } else {
            openActivity(AppendTenantInfoActivity::class.java)
            finish()
        }

    }

    override fun showError(msg: String) {
        ToastyUtils.showError(msg)
    }

    override fun showLoading() {
        CommonDialog.showLoading(mContext!!, Constant.Logging)
    }

    override fun hideLoading() {
        CommonDialog.cancle()
    }

    override fun setLayout(): Int = R.layout.activity_login

    override fun initView() {
        mPresenter.attachView(this)
    }

    override fun initData() {
        et_login_phone.setText(Api.getUserName())
        et_login_password.setText(Api.getPassword())
    }

    override fun onDestroy() {
        super.onDestroy()
        mPresenter.detachView()
    }

    override fun initEvent() {
        btn_login.setOnClickListener { v ->
            var phone = et_login_phone.text.toString()
            var password = et_login_password.text.toString()
            if (phone.isPhone() && password.isNotEmpty()) {
                mPresenter.login(phone, password)
            } else {
                mPresenter.login(phone, password)
                ToastyUtils.showWarning("请填写完整")
            }
        }
    }

}
